<template>
  <div>
<!--    每日一练{{subject_id}}{{subject_name}}{{currentItem}}{{activeCourse}}-->
<!--    {{subjectTabs}}{{tabsActiveName}}{{subjectName}}{{isNotCustom}}-->
    <el-tabs v-model="tabsActiveName" class="demo-tabs">
      <el-tab-pane v-for="item in subjectTabs" :label="item.name" :name="String(item.id)">
        <el-row class="row-bg model" justify="space-between">
          <el-col :span="10">
            <img style="width:100%" src="@/assets/tiku/mryl.jpg">
          </el-col>
          <el-col :span="12">
            <div class="right-body">
              <div class="head-right-contnet">
                <p>
                  每日一练即每天仅只可以练习一次，每次抽取n道题目。每日一练共有2种抽题模式。
                </p>
                <p>默认模式：直接点击开始做题，系统自动随机抽取n题做题</p>
                <p>
                  自定义模式：学员可以自己定义需要抽取哪些章节的题目及数量。
                </p>
              </div>
              <div>
                <el-button type="primary" size="large" @click="CreatedExercise">开始做题</el-button>
                <el-button  @click="dialogExercise = true" size="large">自定义模式</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row class="model">
          <div class="ExerciseTab">
            <el-tabs v-model="activeExercise" class="demo-tabs">
              <el-tab-pane label="练习记录" name="Exercise">
                <div v-if="ExerciseList && ExerciseList.rows && ExerciseList.rows.length">
                  <div v-for="item in ExerciseList.rows">
                    <div @click="toDailyPractice(item)" class="ExerciseItem">
                      <div>
                        <span class="name">{{ proxy.$filters.dateTimeFormat(item.createdAt) }}</span>
                      </div>
                      <div class="exam_history">
<!--                                              {{item}}-->
                        <span v-if="item.answerNum">已作答{{item.answerNum}}题</span>
                        <span v-if="item.correctNum">答对{{item.correctNum}}题</span>
                        <span v-if="item.correctS != null">正确率{{item.correctS}}%</span>
                        <span>{{item.state == 0 ? '未完成':'已完成'}}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <el-empty v-else description="暂无数据" />
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-row>
        <el-row class="mode">
          <div v-if="ExerciseList.pagination">
            <el-pagination
                    background
                    v-model:currentPage="currentPage"
                    :page-size="pageSize"
                    layout="total, prev, pager, next"
                    :total="ExerciseList.pagination.count"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
            />
          </div>
        </el-row>
        <el-dialog v-model="dialogExercise">
          <div class="center-div">
            <div class="title">
              <span>自定义模式</span>
            </div>
            <div class="body">
              <div class="subject_div">
                <el-collapse v-model="activeNames">
                  <el-collapse-item name="default">
                    <template #title>
                      <span style="margin-right: 15px">章节范围</span>
                      <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
                    </template>
                    <el-checkbox-group
                            class="subject-list"
                            v-model="checkboxSubject"
                            @change="handleCheckedCitiesChange"
                    >
                      <el-checkbox v-for="item in subjectList" :key="item.id" :label="item.id">{{item.name }}</el-checkbox>
                    </el-checkbox-group>
                  </el-collapse-item>
                </el-collapse>
              </div>
              <div class="ques_type">
                <div>题目类型</div>
                <div class="mt-4">
                  <el-checkbox-group v-model="checkboxQuesType" @change="getQuestionNum" size="large">
                    <el-checkbox-button v-for="item in TypeCodeList" :label="item">{{TypeCodeMap[item]}}</el-checkbox-button>
                  </el-checkbox-group>
                </div>
              </div>
              <div class="ques_num">
                <div>抽题数量 <span>筛选题数量：{{filterQuestionNum}}</span></div>
                <el-input-number v-model="QuestionNum" :min="1" :max="1000" @change="handleChange" />
              </div>
<!--              <span>选择的章节{{checkboxSubject}} 选择的题型 {{checkboxQuesType}}筛选题目数量{{filterQuestionNum}} 抽题数量 {{QuestionNum}}</span>-->

              <div><el-button @click="resetExerciseModel">重置</el-button><el-button  type="primary" plain :disabled="isDisabled" @click="CreateExerciseModel">确认</el-button></div>
            </div>
          </div>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import goBackHistory from "../../../utils/hook/goBackHistory";
  import {createdExercise, exercise,exerciseTopicFilter} from "@/api/api";
  import {ElMessage,ElMessageBox} from "element-plus";
  import {toRefs,reactive,watchEffect,getCurrentInstance,watch,onMounted} from 'vue'
  import {createdChapter, ExerciseModel, ExerciseModelSubject, subjectList, typeCodeList} from "../../../api/api";
  import {useRoute, useRouter} from "vue-router";
  export default {
    name: "index",
    props:{
      subject_id:{
        type:Number
      },
      subject_name:{
        type:String
      },
      currentItem:{
        type:String
      },
      activeCourse:{
        type:String
      }
    },
    setup(props,{emit}){
      console.log('props',props)
      const { proxy } = getCurrentInstance()
      let router = useRouter();
      let route = useRoute();
      let data = reactive({
        filterQuestionNum:0,
        subjectName:'',
        subjectTabs:[],
        tabsActiveName:null,
        isNotCustom:false,
        create_question_id:null,
        isDisabled:true,
        checkAll:false,
        isIndeterminate:true,
        activeNames:'default',
        pageSize:10,
        currentPage:1,
        ExerciseList:[],//练习列表
        dialogTableVisible : false,
        dialogExercise :false,
        formLabelWidth : '140px',
        checkboxSubject:[], //选择的章节
        subjectList:[], //章节列表
        checkboxQuesType:[], //选择的题型类型
        TypeCodeList:[],//题型列表
        TypeCodeMap:{
          1:"单项选择题",
          2:"多项选择题",
          3:"不定项选择题",
          4:"判断题",
          5:"填空题",
          6:"简答题",
          7:"论述题",
          8:"案例题",
          9:"综合题",
          10:"平台操作题"},
        QuestionNum:1,
        activeExercise:'Exercise'//当前列表
      })
      //筛选题目数量
        let getExerciseTopicFilter = (params) =>{
            exerciseTopicFilter(params).then(res =>{
                data.filterQuestionNum = res.data;
            }).catch(err =>{
                ElMessage({type:'error',message:err.message})
            })
        }

      //查询科目列表
      let getExerciseModelSubject = () =>{
        console.log('data.tabsActiveName',data.tabsActiveName);
        ExerciseModelSubject({subjectID:data.tabsActiveName}).then(res =>{
            console.log('科目模式列表',res)
            if(res.data){
              data.checkboxSubject = res.data.chapterIDs
              data.checkboxQuesType = res.data.types
              data.QuestionNum = res.data.num
              data.isNotCustom = true
              if(data.checkboxSubject.length && data.checkboxQuesType.length){
                  getExerciseTopicFilter({subjectID:data.tabsActiveName,types:data.checkboxQuesType,num:data.QuestionNum,chapterIDs:data.checkboxSubject})
              }
            }else{
              data.isNotCustom = false
            }
        }).catch(err =>{
          ElMessage({type:'error',message:err.message});
        })
      }

      //科目列表
      let getAllSubjectList = () =>{
        let course_id = localStorage.getItem('activeCourse')
        subjectList({courseID:course_id}).then(res =>{
          console.log('科目列表',res)
          data.subjectTabs = res.data;
          data.tabsActiveName = String(res.data[0].id);
          getExerciseModelSubject();
        })
      }
      getAllSubjectList();

      //章节列表
      let getSubjectList = () =>{
          createdChapter({subjectID:String(data.tabsActiveName)}).then(res =>{
            console.log('章节范围',res);
            data.subjectList = res.data
          })
      }

      //题型类型
      let getTypeCodeList = () =>{
        console.log('查询题型的章节id列表',data.checkboxSubject)
        if(data.checkboxSubject.length){
          typeCodeList({chapterIDs:data.checkboxSubject}).then(res =>{
            console.log('题型列表',res)
            data.TypeCodeList = res.data
          })
        }else{
          data.TypeCodeList = [];
        }
      }

      //抽题数量
      const handleChange = (value) => {
        data.QuestionNum = value
      }

      //生成练习题
      let CreatedExercise = () =>{
        if(!data.isNotCustom){
          console.log('生成练习题的科目id为',data.tabsActiveName);
          let params = {subjectID:Number(data.tabsActiveName),isModel:false}
          createdExercise(params).then(res =>{
            let params = router.currentRoute.value;
            let currentItem = props.currentItem;
            goBackHistory.addCurrentPageParams(params,currentItem)
            router.push({name:'DailyPractice',params:{subject_name:data.subjectName,id:res.data.id,state:0}});
          }).catch(err =>{
            console.log('默认生成每日一练');
            if(err.message == '今日已生成每日一练库'){
              let params = router.currentRoute.value;
              let currentItem = props.currentItem;
              goBackHistory.addCurrentPageParams(params,currentItem);
              router.push({name:'DailyPractice',params:{subject_name:data.subjectName,id:data.ExerciseList.rows[0].id,state:data.ExerciseList.rows[0].state}});
            }else{
              ElMessage({type:'error',message:err.message})
            }
          })
        }else{
          let params = {subjectID:Number(data.tabsActiveName),isModel:true}
          createdExercise(params).then(res =>{
            console.log('res',res);
            router.push({name:'DailyPractice',params:{subject_name:data.subjectName,id:res.data.id,state:0}});
          }).catch(err =>{
            if(err.message == '今日已生成每日一练库'){
              let params = router.currentRoute.value;
              let currentItem = props.currentItem;
              goBackHistory.addCurrentPageParams(params,currentItem)
              router.push({name:'DailyPractice',params:{subject_name:data.subjectName,id:data.ExerciseList.rows[0].id,state:data.ExerciseList.rows[0].state}});
            }else{
              ElMessage({type:'error',message:err.message})
            }
          })
        }
      }

      //练习列表
      let getExercise = () =>{
        exercise({subjectID:data.tabsActiveName,page:data.currentPage,pageSize:data.pageSize}).then(res =>{
          console.log('练习列表',res)
          data.ExerciseList = res.data
        }).catch(err =>{
          ElMessage({type:'error',message:err.message})
        })
      }

      //重置练习题参数
      let resetExerciseModel = () =>{
        data.checkboxSubject = data.checkboxQuesType = data.TypeCodeList = [];
        data.QuestionNum = 1;
        data.filterQuestionNum = 0;
      }

      //自定义生成练习题
      let CreateExerciseModel = () =>{
          if(data.QuestionNum <= data.filterQuestionNum){
              ExerciseModel({subjectID:data.tabsActiveName,types:data.checkboxQuesType,num:data.QuestionNum,chapterIDs:data.checkboxSubject}).then(res =>{
                  console.log('自定义生成的练习题集合',res)
                  data.create_question_id = res.id;
                  data.dialogExercise = false;
                  resetExerciseModel();
                  getExerciseModelSubject();
                  ElMessage({type:'success',message:'自定义模式已生成'})
              })
          }else{
              ElMessage({type:'error',message:'练习题数量超出筛选题数量'})
          }
      }

      let getQuestionNum = () =>{
          let types = data.checkboxQuesType;
          let chapterIDs = data.checkboxSubject;
          getExerciseTopicFilter({subjectID:data.tabsActiveName,types:types,num:data.QuestionNum,chapterIDs:chapterIDs});
      }

      //跳转至每日一练开始答题
      let toDailyPractice = (item) =>{
        console.log('练习id',item.id)
        console.log('科目名称',data.subjectName)
        if(item.state == 0){
          ElMessageBox.confirm(
                  '是否继续上次未完成的试卷？',
                  '温馨提示',
                  {
                    confirmButtonText: '继续作答',
                    cancelButtonText: '退出',
                    type: 'warning',
                  }
          )
                  .then(() => {
                    let params = router.currentRoute.value;
                    let currentItem = props.currentItem;
                    goBackHistory.addCurrentPageParams(params,currentItem)
                    router.push({name:'DailyPractice',params:{subject_name:data.subjectName,id:item.id,state:item.state}})
                  })
                  .catch(() => {

                  })
        }else{
          router.push({name:'DailyPractice',params:{subject_name:data.subjectName,id:item.id,state:item.state}})
        }
      }

      const handleSizeChange = (val) => {
        console.log(`${val} items per page`)
        data.pageSize = val;
        getExercise();
      }
      const handleCurrentChange = (val) => {
        console.log(`current page: ${val}`)
        data.currentPage = val;
        getExercise();
      }

      const handleCheckAllChange = (val) => {
        data.checkboxSubject = val ? data.subjectList.map(item => item.id) : []
        data.isIndeterminate = false
          getExerciseTopicFilter({subjectID:data.tabsActiveName,types:data.checkboxQuesType,num:data.QuestionNum,chapterIDs:data.checkboxSubject})
      }
      const handleCheckedCitiesChange = (value) => {
        getExerciseTopicFilter({subjectID:data.tabsActiveName,types:data.checkboxQuesType,num:data.QuestionNum,chapterIDs:data.checkboxSubject})
        const checkedCount = value.length
        data.checkAll = checkedCount === data.subjectList.length
        data.isIndeterminate = checkedCount > 0 && checkedCount < data.subjectList.length
      }

      //监听章节展示所选择的题型类型

      watch(() => data.tabsActiveName,() =>{
        if(data.tabsActiveName){
          console.log('data.tabsActiveName---',data.tabsActiveName);
          data.subjectName = data.subjectTabs.filter(item => item.id == Number(data.tabsActiveName))[0].name;
          emit('changeSubjectName',data.subjectName);
          getSubjectList();
          getExercise();
          resetExerciseModel();
          getExerciseModelSubject();
        }
      })

      watch(() => props.activeCourse,() =>{
        getAllSubjectList();
      })
      watchEffect(() =>{
        let activeCourse = props.activeCourse;
        console.log('课程activeName',activeCourse)


        if(data.checkboxSubject){
          getTypeCodeList();
        }
        if(data.checkboxSubject.length && data.checkboxQuesType.length){
          data.isDisabled = false
        }else{
          data.isDisabled = true
        }
      })

      return{
        getQuestionNum,
        handleCheckAllChange,
        handleCheckedCitiesChange,
        proxy,
        handleSizeChange,
        handleCurrentChange,
        toDailyPractice,
        resetExerciseModel,
        handleChange,
        getTypeCodeList,
        getExerciseModelSubject,
        CreateExerciseModel,
        ...toRefs(data),
        getExercise,
        CreatedExercise
      }
    }
  }
</script>

<style>
.ques_type .el-checkbox-group .el-checkbox-button{
  margin-right: 20px;
}
.ques_type .el-checkbox-group.el-checkbox-button__inner{
  border-left:1px;
}
.el-checkbox-button:first-child .el-checkbox-button__inner,.el-checkbox-button:last-child .el-checkbox-button__inner{
  border-radius: unset;
}
.mt-4 .el-checkbox-button__inner{
  border-left: 1px solid #c8c9cc;
}
</style>

<style scoped>
  .model{
    margin-bottom: 20px;
  }
  .ques_type{
    padding: 20px 0px;
    min-height: 70px;
  }
  .ques_type div{
    margin-bottom: 10px;
  }
  .ques_num{
   padding: 20px 0px;
  }
  .ques_num div{
    margin-bottom: 10px;
  }
  .subject-list{
    display: flex;
    flex-direction: column;
  }
  .exam_history :not(:last-child){
    margin-right: 20px;
  }
  .exam_history :not(:first-child){
    font-weight: 400;
    font-size: 12px;
    color: rgba(42, 130, 228, 1);
  }
  .exam_history :first-child{
    font-weight: 400;
    font-size: 1px;
    color: rgba(153, 153, 153, 1);
  }
  .ExerciseItem .name{
    color: rgba(11, 67, 128, 1);
    font-size: 14px;
    font-weight: 400;
  }
  .ExerciseTab{
    width: 100%;
    margin-bottom: 20px;
  }
  .ExerciseItem{
    display: flex;
    justify-content: space-between;
    padding: 5px 20px;
    background-color:  rgba(248, 248, 248, 1);
    margin-bottom: 10px;
    border-radius: 10px;
    cursor: pointer;
  }
  .center-div .title{
    display: flex;
    justify-content: center;
    font-size: 1.5rem;
    color: rgba(36, 127, 224, 1);
  }
  .center-div .body{
    padding: 1rem;

  }
  .dialogExercise .center-div{
    padding: 20px;
  }
  .head-right-contnet{
    color: rgba(153, 153, 153, 1);
    font-size: 14px;
    line-height: 1.875rem;
    margin-bottom: 20px;
  }
  .right-body{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
</style>
